package com.downhometech.productcalculator.activities;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.ConsoleHandler;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.util.TypedValue;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

import com.downhometech.productcalculator.controllers.ProductController;
import com.downhometech.productcalculator.controllers.SquareIntegration;
import com.downhometech.productcalculator.models.Cart;
import com.downhometech.productcalculator.models.CartItem;
import com.downhometech.productcalculator.models.Product;
import com.downhometech.productcalculator.models.Setting;

public class ShowCartActivity extends DefaultActivity 
{
    private Context context;
    private static ArrayList<CartItem> cartList = null;
    private static ArrayList<String[]> totals = null;
    private static String[] header = null;
    private Cart cart = null;
	private static class EfficientAdapter extends BaseAdapter 
	{
		private LayoutInflater mInflater;
		private Context parentContext;
		private DecimalFormat doubleFormat = new DecimalFormat("##.00");
		private Product product;
		private CartItem cartItem;
		
		public EfficientAdapter(Context context) 
		{
			mInflater = LayoutInflater.from(context);
			parentContext = context;
		}

		public int getCount() {
			//all items in cart + totals + 1 row for header
			return cartList.size() + totals.size() + 1;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) 
		{
			ViewHolder holder;
			
			if (convertView == null) 
			{
				convertView = mInflater.inflate(R.layout.showcart_item, null);
				holder = new ViewHolder();
				holder.itemName = (TextView) convertView.findViewById(R.id.ItemName);
				holder.itemPrice = (TextView) convertView.findViewById(R.id.ItemPrice);
				holder.itemQty = (TextView) convertView.findViewById(R.id.ItemQty);
				holder.itemDiscount = (TextView) convertView.findViewById(R.id.ItemDiscount);
				holder.itemCost = (TextView) convertView.findViewById(R.id.ItemCost);
				holder.item = (RelativeLayout) convertView.findViewById(R.id.Item);

				convertView.setTag(holder);
					
			}
			else 
			{
				holder = (ViewHolder) convertView.getTag();
			}
			if (position == 0)
			{
				holder.itemName.setText(header[0]);
				holder.itemQty.setText(header[1]);
				holder.itemPrice.setText(header[4]);
				holder.itemCost.setText(header[2]);
				holder.itemDiscount.setText(header[3]);
				
			}
			else if (position -1 < cartList.size())
			{
				cartItem = cartList.get(position - 1);
				product = cartItem.getProduct();
				holder.itemName.setText(product.getName());
				
				holder.itemQty.setText(ProductController.formatDouble(cartItem.getQuantity()));
				holder.itemPrice.setText(ProductController.formatCurrency(cartItem.getTotalPrice()));
				if (cartItem.isListPriceUsed())
					holder.itemCost.setText(ProductController.formatCurrency(product.getListedPrice()));
				else
					holder.itemCost.setText(ProductController.formatCurrency(product.getCustomPrice()));

				holder.itemDiscount.setText(ProductController.formatCurrency(cartItem.getDiscountCalculated()));
				holder.item.setBackgroundResource(R.drawable.button_highlight);
			}
			else
			{
				holder.itemName.setText(totals.get((position - 1) - cartList.size())[0]);
				holder.itemPrice.setText(totals.get((position - 1) - cartList.size())[1]);
			}

			return convertView;
		}

		
		class ViewHolder 
		{
			TextView itemName;
			TextView itemPrice;
			TextView itemQty;
			TextView itemCost;
			TextView itemDiscount;
			RelativeLayout item;
		}
	}

	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showcart);
	    ProductCalculator application = ((ProductCalculator)getApplicationContext());
	    ProductController controller = new ProductController(this);
	    cart = application.getProductCart();  
	    
	    DecimalFormat format = new DecimalFormat("##.000");
	    String taxRateDisplay = "";
	    if (cart.isTaxRateIsPercent()) { taxRateDisplay = "(" + format.format(cart.getTaxRate() * 100) + " %)"; }
	    else { taxRateDisplay = "(" + cart.getTaxRate() + ")"; }
	    
	    String shippingRateDisplay = "";
	    if (cart.isShippingRateIsPercent()) { shippingRateDisplay = "(" + format.format(cart.getShippingRate() * 100) + " %)"; }
	    else { shippingRateDisplay = "(" + cart.getShippingRate() + ")"; }
	   	    
	    cartList = cart.getCartItems();
	    //Product product = new Product(0, "Subtotal", "", 0, false, 0);
	    header = new String[] { "Name", "Qty", "Cost", "Disc", "Total" };
	    
	    totals = new ArrayList<String[]>();
	    totals.add(new String[] {controller.getAndroidString(R.string.TextCartSubTotal), cart.getProductTotalFormatted() });
	    totals.add(new String[] {controller.getAndroidString(R.string.TextCartTaxes) + " " + taxRateDisplay, cart.getTaxTotalFormatted() });
	    totals.add(new String[] {controller.getAndroidString(R.string.TextCartShipping) + " " + shippingRateDisplay, cart.getShippingTotalFormatted() });
	    totals.add(new String[] {controller.getAndroidString(R.string.TextCartTotal) + " ", cart.getTotalFormatted() });

	    Button homeButton = (Button) findViewById(R.id.ShowCart_HomeButton);
		homeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent(ShowCartActivity.this, CartActivity.class);
				startActivity(intent);	   		   
			}
		});	    
	    
		ListView listView = (ListView) findViewById(R.id.ShowCartListView);
		listView.setAdapter(new EfficientAdapter(this));
	
		listView.setOnItemClickListener(new OnItemClickListener() 
		{
			public void onItemClick(AdapterView<?> adapter, View view, int adapterLocation, long arg3) 
			{
				if (adapterLocation <= cartList.size() && adapterLocation > 0)
				{
					CartItem cartItem = (CartItem)cartList.get(adapterLocation - 1);
					Intent intent = new Intent(ShowCartActivity.this, ProductDescriptionActivity.class);
					intent.putExtra("_cartItem", cartItem);
					startActivity(intent);	
					finish();
				}
			}
		});	

	}
	public boolean onCreateOptionsMenu(Menu menu)
	{
		 MenuInflater inflater = getMenuInflater();
		 inflater.inflate(R.menu.menu_showcart, menu);
		 return true;
	}
	  @Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		super.onPrepareOptionsMenu(menu);
		SquareIntegration square = new SquareIntegration(this);
		if (!square.isSquareInstalled())
		{
			MenuItem item = menu.findItem(R.id.menu_squareUp);
			item.setVisible(false);
			item.setEnabled(false);
		}
	
		return true;
	}	
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		Intent intent = null;
		switch(item.getItemId())
		{
			case R.id.menu_editDefaultValues:
				intent = new Intent(this, EditSettingsActivity.class);
				startActivity(intent);
				finish();
				return true;
			case R.id.menu_goHome:
				intent = new Intent(this, CartActivity.class);
				startActivity(intent);	 
				finish();
				return true; 
			case R.id.menu_squareUp:
				SquareIntegration square = new SquareIntegration(this);
				ProductController controller = new ProductController(this);
				Setting setting = controller.getSettingById(Setting.CHECKOUT_DESCRIPTION);
				if (setting != null) { square.addCart(setting.getValue(), cart.getTotal()); }
				else { square.addCart("", cart.getTotal()); } 
				square.checkOutWithSquare();
				return true; 				
		}
		return false;
	}

}

